<template>
  <page-wrap
    ref="pageWrap"
    hideTab
    back
    :bg-color="uNavColor"
    :showTop="showTop"
    :dark="loaded ? false : true"
    :hideSafeArea="true"
    title="重点群体个人档案"
  >
    <view class="person-info" :style="'padding-top:' + navHeight + 'px;'">
      <view class="loading" v-if="pageLoading">
        <u-loading :show="pageLoading" size="42" color="#f75a3e"></u-loading>
      </view>
      <view class="empty" v-if="!showForm">
        <u-empty text="暂无数据" mode="search"></u-empty>
      </view>
      <template v-if="showForm">
        <view class="logo-wrap">
          <image class="logo" :src="formConfigData.logoUrl" />
          <text class="logo-text">{{ formConfigData.name }}</text>
        </view>
        <view class="basic">
          <view class="basic-form-wrap">
            <u-form
              class="basic-form"
              label-position="top"
              ref="uForm"
              :model="form"
              :error-type="['message']"
            >
              <view
                class="data-item"
                v-for="(item, index) in formConfigData.dataItem"
                :key="index"
              >
                <view class="top-title-wrap">
                  <view class="line"></view>
                  <view class="top-title">{{ item.topTitle }}</view>
                </view>
                <block v-for="(_item, _index) in item.dataSet" :key="_index">
                  <view
                    class="form-item-wrap"
                    @click.capture="handleSelect(_item, _index)"
                  >
                    <u-form-item
                      :class="{
                        pick:
                          _item.componentType === 'datePicker' ||
                          _item.componentType === 'select'
                      }"
                      :label="_item.setName"
                      :prop="_item.setKey"
                    >
                      <u-input
                        v-if="!getComponentType(_item.componentType)"
                        class="form-input"
                        :value="form[_item.setKey]"
                        :disabled="
                          forbidEditFieldFn(_item.setKey) ||
                          _item.componentType === 'datePicker' ||
                          _item.componentType === 'select'
                        "
                        :placeholder="`请填写${_item.setName}`"
                        :clearable="true"
                        @input="(val) => handleInput(val, _item)"
                      />
                      <u-checkbox-group
                        v-if="_item.componentType === 'checkbox'"
                        v-model="form[_item.setKey]"
                        @change="(val) => checkboxGroupChange(val, _item)"
                      >
                        <u-checkbox
                          v-for="checkbox in _item.customData"
                          v-model="checkbox.checked"
                          active-color="#f75a3e"
                          :key="checkbox.key"
                          :name="checkbox.value"
                        >
                          {{ checkbox.value }}
                        </u-checkbox>
                      </u-checkbox-group>
                    </u-form-item>
                  </view>
                </block>
              </view>
            </u-form>
          </view>
          <view class="btn-wrap">
            <u-button
              class="save-btn"
              type="primary"
              shape="circle"
              :loading="loading"
              @click="handleSave"
              >提 交</u-button
            >
          </view>
        </view>
      </template>
    </view>
    <!-- 下拉选择 -->
    <u-select
      class="form-select"
      v-model="showSelect"
      :list="currentCustomData"
      @confirm="handleConfirm"
    ></u-select>
    <!-- 时间选择 -->
    <u-picker
      class="form-time"
      mode="time"
      v-model="showPicker"
      :params="pickerParam"
      :start-year="start"
      :end-year="end"
      @confirm="handleConfirm"
    ></u-picker>
    <LoginDialog
      ref="loginDialog"
      @loginSuccessBack="loginSuccessBack"
    ></LoginDialog>
    <u-modal
      v-model="showTip"
      :show-cancel-button="true"
      :show-confirm-button="true"
      confirm-color="#f75a3e"
      cancel-color="#ece9e9"
      :content="content"
      @confirm="handleModelConfirm"
    ></u-modal>
  </page-wrap>
</template>

<script>
import { formatTime } from '@/utils/handle';
import { componentTypeMap } from '@/utils/dataMap';
import { offlineView, offlineEdit } from '@/api/modules/career';
import RegionFilter from '@/components/RegionFilter';
import LoginDialog from '@/components/LoginDialog';
export default {
  components: {
    RegionFilter,
    LoginDialog
  },
  data() {
    return {
      personId: uni.getStorageSync('person-id').slice(2) || undefined,
      navHeight: getApp().globalData.navHeight,
      userInfo: {},
      showTop: false,
      pageLoading: true,
      showForm: false,
      uNavColor: '#daf6f8',
      form: {},
      pickerParam: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
      start: new Date().getFullYear() - 70,
      end: new Date().getFullYear(),
      showPicker: false,
      showSelect: false,
      currentCustomData: [],
      loading: false,
      currentItem: {},
      formConfigData: {
        dataItem: [],
        logoUrl: '',
        name: '',
        rules: [],
        type: '',
        value: ''
      },
      cardType: uni.getStorageSync('offline_cardType'),
      type: uni.getStorageSync('offline_type'),
      setCode: uni.getStorageSync('offline_setCode'),
      value: uni.getStorageSync('offline_value'),
      offline_personId: uni.getStorageSync('offline_personId'),
      content: '您拥有一张寮步重点人群服务的职途卡，是否去使用？',
      showTip: false
    };
  },
  created() {},
  onPageScroll(res) {
    this.showTop = res.scrollTop > 0;
  },
  mounted() {},
  onShow() {},
  onLoad(opt) {
    this.offlineViewFn();
  },
  onReady() {},
  methods: {
    handleInput(val, item) {
      this.form[item.setKey] = val;
    },
    offlineViewFn() {
      this.pageLoading = true;
      const params = {
        cardType: this.cardType,
        type: this.type,
        setCode: this.setCode,
        value: this.value,
        personId: this.offline_personId
      };
      offlineView(params)
        .then((res) => {
          if (res.code == 200) {
            // // 先去掉用户不能编辑的项
            // const index = res.data.dataItem.findIndex(
            //   (item) => item.topTitle === '服务跟踪详情'
            // );
            // res.data.dataItem.splice(index, 1);

            res.data.dataItem.forEach((item) => {
              item.dataSet.forEach((_item) => {
                // 不展示table类型的数据
                if (_item.componentType !== 'table') {
                  if (
                    typeof _item.setValue === 'object' &&
                    _item.setValue !== null
                  ) {
                    this.$set(
                      this.form,
                      _item.setKey,
                      _item.setValue.join(',')
                    );
                  } else {
                    this.$set(this.form, _item.setKey, _item.setValue);
                  }
                }
                if (_item.componentType === 'checkbox') {
                  _item.customData.forEach((checkbox) => {
                    this.$set(
                      checkbox,
                      'checked',
                      _item.setValue.includes(checkbox.key)
                    );
                  });
                }
              });
            });
            Object.keys(res.data).forEach((key) => {
              this.$set(this.formConfigData, key, res.data[key]);
            });
            this.showForm = true;
            this.$nextTick(() => {
              this.$refs.uForm.setRules(this.formConfigData.rules);
            });
          } else {
            uni.showToast({ icon: 'none', title: res.status_desc });
          }
        })
        .finally(() => {
          this.pageLoading = false;
        });
    },
    checkboxGroupChange(val, item) {
      const temp = [];
      item.customData.forEach((checkbox) => {
        if (checkbox.checked) {
          temp.push(checkbox.key);
        }
      });
      this.form[item.setKey] = temp.join(',');
    },
    forbidEditFieldFn(key) {
      return this.formConfigData.forbidEditField.includes(key);
    },
    getComponentType(type) {
      return componentTypeMap[type];
    },
    handleSelect(item) {
      this.currentItem = item;
      if (
        item.componentType == 'datePicker' ||
        item.componentType == 'select'
      ) {
        this.showPicker = true;
      }
    },
    handleConfirm(e) {
      if (Array.isArray(e)) {
        this.$set(this.form, this.currentItem.setKey, e[0].key);
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        this.$set(this.form, this.currentItem.setKey, time);
      }
      setTimeout(() => {
        this.$refs.uForm.validate();
      }, 0);
    },
    handleSave() {
      this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
      if (!this.personId) {
        this.$refs.loginDialog.setVisibility(true);
        return;
      }
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let dataSet = [];
          Object.entries(this.form).forEach((item) => {
            dataSet.push({
              setKey: item[0],
              setValue: this.formatValue(item[1])
            });
          });
          const params = {
            cardType: this.cardType,
            personId: this.offline_personId,
            newPersonId: uni.getStorageSync('person-id').slice(2),
            type: 'edit',
            value: this.value,
            setCode: this.setCode,
            dataSet
          };
          offlineEdit(params).then((res) => {
            this.loading = false;
            if (res.code == 200) {
              uni.showToast({ icon: 'none', title: '信息已保存' });
              this.showTip = true;
            } else {
              uni.showToast({ icon: 'none', title: res.status_desc });
            }
          });
        } else {
          this.loading = false;
          uni.showToast({ icon: 'none', title: '请完善信息后保存' });
        }
      });
    },
    formatValue(value) {
      const type = this.getType(value);
      // 如果是数组就把数组转成字符串，如果是对象就转成json字符串
      if (type == 'array') {
        return value.join(',');
      } else if (type == 'object') {
        // 如果是空对象，则赋值为空字符串
        if (Object.keys(value).length === 0) {
          return '';
        } else {
          // 如果是有值的对象，则转成json字符串
          return JSON.stringify(value);
        }
      } else if (type == 'null' || type == 'undefined') {
        return '';
      } else {
        return value;
      }
    },
    getType(obj) {
      return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
    },
    handleModelConfirm() {
      uni.navigateTo({ url: '/pagesSub/userCenter/careerPathV2/index' });
      this.showTip = false;
    },
    loginSuccessBack() {
      this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
      if (this.personId) {
        this.handleSave();
      }
    }
  }
};
</script>

<style lang="scss">
.person-info {
  width: 100%;
  background-image: url('https://img3.job1001.com/ypMp/elan/images/careerPath/person-info-bg.png?v=1');
  background-repeat: no-repeat;
  background-size: 100% 100vh;
  color: #ece9e9;
  .loading,
  .empty {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .logo-wrap {
    display: flex;
    align-items: center;
    padding-left: 32rpx;
    margin-top: 28rpx;
    .logo {
      width: 76rpx;
      height: 76rpx;
      margin-right: 8rpx;
    }
    .logo-text {
      font-weight: bold;
      font-size: 28rpx;
      color: #333333;
    }
  }
  .basic {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 16rpx 16rpx 36rpx;
    box-sizing: border-box;
    .basic-form-wrap {
      flex-grow: 1;
      padding-bottom: calc(80rpx + constant(safe-area-inset-bottom));
      padding-bottom: calc(80rpx + env(safe-area-inset-bottom));
      ::v-deep .u-form {
        background: $uni-bg-color;
        border-radius: 24rpx;
        .u-form-item {
          .u-form-item--left__content__label {
            font-weight: bold;
            font-size: 30rpx;
            color: #222222;
          }

          .btn-group {
            padding: 0 24rpx;
            line-height: 102rpx;
            .cancel,
            .confirm {
              padding: 0 16rpx;
            }
          }
        }
      }
      .basic-form {
        display: flex;
        flex-direction: column;
        background-color: #f4f6f8;
        .data-item {
          padding: 32rpx 20rpx 0 20rpx;
          border-radius: 32rpx;
          margin-bottom: 24rpx;
          background-color: #fff;
          .top-title-wrap {
            display: flex;
            align-items: center;
            padding-bottom: 42rpx;
            .line {
              width: 8rpx;
              height: 34rpx;
              background: #f75a3e;
              border-radius: 200rpx;
            }
            .top-title {
              font-family: PingFang-SC, PingFang-SC;
              font-weight: bold;
              font-size: 36rpx;
              color: #222222;
              margin-left: 16rpx;
            }
          }
        }
      }
    }
    .save-btn {
      flex-shrink: 0;
      margin: 82rpx 0 4rpx;
      width: 100%;
    }
    .btn-wrap {
      position: fixed;
      bottom: calc(constant(safe-area-inset-bottom));
      bottom: calc(env(safe-area-inset-bottom));
      left: 0;
      width: 100vw;
      padding: 0 32rpx;
      z-index: 999;
    }
  }
  .form-cms {
    ::v-deep .fc-wrap {
      padding: 0 32rpx 32rpx;
      box-sizing: border-box;
      .title {
        line-height: 90rpx;
        text-align: center;
        font-size: $uni-font-size-lg;
      }
      .u-field {
        padding: 24rpx 0;
      }
      .send-code {
        color: $u-type-primary;
      }
      .confirm-btn {
        margin-top: 44rpx;
      }
    }
  }
}
</style>
